const Router = require('koa-router');
const http = require('http');
const querystring=require('querystring');

const router = new Router();

// 测试语义识别接口
const common=require('./utils');
router.get('/semantic',(ctx,next)=>{
    common.chatRobot('你好');
    ctx.body=`<h1>测试语义识别接口</h1>`;
});

// 测试get请求
router.get('/api/gets', (ctx, next) => {
    http.get('http://106.13.182.88:8081/get.php', (res) => {
        ctx.body = `<h1>测试get请求</h1>`;
        let rawData = '';
        // 开始接收数据
        res.on('data', (chunk) => {
            rawData += chunk;
        });
        // 接收数据完毕, 并且格式化数据
        res.on('end', () => {
            console.log(JSON.parse(rawData), 'data');
        });
        res.on('error', (err) => {
            console.log(err.message);
        });
    });
    ctx.body = '<h1>测试get请求</h1>';

});


// 测试post请求
router.get('/api/posts', (ctx, next) => {
    ctx.body = '<h1>测试post请求</h1>';
    // {} => key=val&key=val
    const postData = querystring.stringify({
        'msg': '你好世界'
    });

    const options = {
        // 不需要写http://前缀
        hostname: '106.13.182.88',
        port: 8081,
        path: '/post.php',
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': Buffer.byteLength(postData)
        }
    }
    const req = http.request(options, (res) => {
        // console.log(`状态码: ${res.statusCode}`);
        // console.log(`响应头: ${JSON.stringify(res.headers)}`);
        res.setEncoding('utf8');
        let rawData = '';
        res.on('data', (chunk) => {
            //   console.log(`响应主体: ${chunk}`);
            rawData += chunk;
        });
        res.on('end', () => {
            //   console.log('响应中已无数据');
            const json = JSON.parse(rawData);
            console.log(json);
        });
    });

    req.on('error', (e) => {
        console.error(`请求遇到问题: ${e.message}`);
    });
    // 将数据写入请求主体。
    req.write(postData);
    req.end();
});


module.exports = router;